﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RH.Common.Extensions;
using RH.Domain;
using RH.Web.ViewModels;
using RH.Web.Utility;
using AutoMapper;
using System.Data;
using RH.Web.ViewModels.UtilityModels;


namespace RH.Web.Areas.Private.Controllers
{
    [Authorize(Roles = "Company Admin,Company User,Admin")]
    public class ContactController : BaseController
    {
        private AppEntities _Context = null;
        private EntityRepository _Repository = null;
        
		#region Constructors
		public ContactController()
		{
            _Context = new AppEntities();
            _Repository = new EntityRepository(_Context);
		}

		public ContactController(UserViewModel currentUser)
			: base(currentUser)
        {
        }
		#endregion Constructors

		#region Action Methods
        public ActionResult Index()
        {
            return RedirectToAction("List");
        }
		/// <summary>
        /// Gets a Contact from Database to edit
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
		public ActionResult Edit(int id = 0, String IsSaved = null, String IsAdded = null)
        {
            Contact entity = id == 0 ? new Contact() : _Repository.GetContactByID(id); //_Context.Contacts.FirstOrDefault(P => P.ID == id);
            if (id == 0)
            {
                entity.IsActive = true;
                entity.CompanyID = LoggedInUser.Company.ID;
            }

            ContactViewModel viewModel = Mapper.Map<Contact, ContactViewModel>(entity);
            TempData[AppConstants.ViewDataKeys.ADDED] = IsAdded;
            TempData[AppConstants.ViewDataKeys.SAVED] = IsSaved;
            return View(viewModel);
        }

        /// <summary>
        /// Saves Contact Information into the Database
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(ContactViewModel viewModel)
        {
            //if (!ModelState.IsValid)
            //    return View(viewModel);

            if (viewModel.CompanyID != LoggedInUser.Company.ID)
                return RedirectToAccessDenied();

            Contact entity = null;
            if (viewModel.ID == 0)
            {
                entity = new Contact();                
                _Context.AddToContacts(entity);                
            }
            else
                entity = _Repository.GetContactByID(viewModel.ID);
            
            entity = Mapper.Map<ContactViewModel, Contact>(viewModel, entity);
            entity.Address = Mapper.Map<AddressViewModel, Address>(viewModel.Address, entity.Address);
            //if (viewModel.Address.ID == 0)
            //    entity.Address.CreatedOn = DateTime.Now;

            entity.Address.ModifiedBy = LoggedInUser.ID;
            //entity.Address.ModifiedOn = DateTime.Now;
            _Context.SaveChanges();
            ///Update the cached UserInfo in Session
            UserInfo.RefreshUserInfo(_Repository);
            
            String url = String.Format("Edit/{0}", entity.ID);
            if (viewModel.ID == 0)
                return RedirectToAction(url, new { IsAdded = "True" });

            return RedirectToAction(url, new { IsSaved = "True" });
        }

        public ActionResult CreateUser(int id = 0)
        {
            Contact entity = id == 0 ? new Contact() : _Context.Contacts.FirstOrDefault(P => P.ID == id && P.CompanyID == LoggedInUser.Company.ID);
            if (entity == null)
            {
                return RedirectToAction("List");
            }
            else
            {
                //if (id == 0)
                //{
                entity.IsActive = true;
                entity.CompanyID = LoggedInUser.Company.ID;
                //}

                //RegisterModel viewModel = Mapper.Map<Register, RegisterModel>(entity);
                ViewBag.ContactEmail = "CreateUser@Yahoo.com";
                return View();
            }

            //Contact entity = id == 0 ? new Contact() : _Context.Contacts.FirstOrDefault(P => P.ID == id);
            //if (id == 0)
            //{
            //    entity.IsActive = true;
            //    entity.CompanyID = LoggedInUser.Company.ID;
            //}

            //ContactViewModel viewModel = Mapper.Map<Contact, ContactViewModel>(entity);
            //return View(viewModel);
        }

        //[HttpPost]
        //public ActionResult CreateUser(RegisterModel model)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        if (_Context.IsDuplicateEmail(model.Email))
        //            ModelState.AddModelError("", "The User ID address is already taken. Please choose another.");
        //        else
        //        {
        //            User user = new User();
        //            user.UserName = model.Email;
        //            user.Password = model.Password;
        //            user.GroupID = ConfigReader.UserGroupIDOfSiteUser;
        //            user.IsActive = true;

        //            _Context.AddToUsers(user);
        //            _Context.SaveChanges();
        //            //// Attempt to register the user
        //            //MembershipCreateStatus createStatus;
        //            //Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

        //            //if (createStatus == MembershipCreateStatus.Success)
        //            //{
        //            //    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
        //            //    return RedirectToAction("Index", "Home");
        //            //}
        //            //else
        //            //{
        //            //    ModelState.AddModelError("", ErrorCodeToString(createStatus));
        //            //}

        //            return RedirectToAction("List");
        //            //return RedirectToAction("Register", new { msg = "True" });
        //        }
        //    }

        //    // If we got this far, something failed, redisplay form
        //    return View(model);
        //}
		
		#endregion Action Methods

        public ActionResult List()
        {
            //UtilityDAO dao = new UtilityDAO();
            //RH.Domain.DbParameter[] parameters = new[]{
            //    new RH.Domain.DbParameter("@CompanyID", LoggedInUser.Company.ID)
            //};
            //DataSet ds = dao.GetDataSet(DbObject.SP.GET_CONTACTS_BY_COMPANY, parameters, true);
            //ViewBag.LinkFormat = "/Private/Contact/Edit/{0}";

            //ViewBag.AnotherLinkText = "CreateUser";
            //ViewBag.AnotherLinkFormat = "javascript:void(0); MakeUser({0},'{1}')";
            //ViewBag.AnotherLinkFieldName = "ID";
            //return View(ds.Tables[0]);


            UtilityDAO dao = new UtilityDAO();
            RH.Domain.DbParameter[] parameters = new[]{
                new RH.Domain.DbParameter("@CompanyID", LoggedInUser.Company.ID)
            };
            DataSet ds = dao.GetDataSet(DbObject.SP.GET_CONTACTS_BY_COMPANY, parameters, true);
            //DataTable dt = BuildDataTable();
            //DateTime start = DateTime.Now;
//            ListConfig config = RH.Web.ViewModels.UtilityModels.ListConfigBuilder.Build(
//                @"Group Name{ ID | Name | UserName  }, 
//                Personal Info{Personal Email | Office Email | Cell Phone}",
//                ds.Tables[0], true, "/Private/Contact/Edit/{0}",
//                true, "javascript:void(0); MakeUser({0},'{1}')");

            //Picture{Image:<img src='/ProductImages/{0}' alt='{1}' title='{2}' />(ThumbImage ~ ID ~ Name)},
            //Description{Description}

            //ViewBag.ListConfig = config;
            //ViewData[AppConstants.ViewDataKeys.LIST_CONFIG] = config;

            ListConfig listConfig = new ListConfig(ds.Tables[0], null);
            return View(listConfig);
        }

        [HttpPost]
        public int Delete(int id)
        {
            Contact contact = _Context.Contacts.FirstOrDefault(P => P.ID == id);
            if (contact != null)
            {
                contact.IsDeleted = true;
                _Context.SaveChanges();
                UserInfo.RefreshUserInfo(_Repository);
                return 1;
            }
            return 0;
        }

        public String GetUserInfo(int id)
        {
            User entity = _Context.Users.FirstOrDefault(P => P.ID == id);
            if (entity == null)
                return String.Empty;
            UserViewModel viewModel = new UserViewModel();
            viewModel.ID = entity.ID;
            viewModel.ContactID = entity.ContactID.GetValueOrDefault();
            viewModel.UserName = entity.UserName;
            viewModel.GroupID = entity.GroupID;
            viewModel.IsActive = entity.IsActive;
            return viewModel.ToJSON();
        }

        /// <summary>
        /// Converts a Contact to a User and enables for further editing option
        /// </summary>
        /// <param name="user"></param>
        /// <returns>
        /// 1. Returns -1 if the requested user does not exist for edit.
        /// 2. Returns -2 if the username is already taken
        /// 3. Returns >0 if everything is ok, then returns the saved user's ID 
        /// </returns>
        [HttpPost]
        public int SaveUser(UserViewModel user)
        {
            User entity = user.ID > 0 ? _Context.Users.FirstOrDefault(P => P.ID == user.ID) : new User();
            if (entity == null)
                return -1;
            ///Check for dulicate user name
            if (String.Compare(user.UserName, entity.UserName, true) != 0)
            {
                if (_Context.IsDuplicateUserName(user.UserName, user.ID))
                    return -2;
            }
            if (user.ID <= 0)
                _Context.AddToUsers(entity);
            
            entity.GroupID = user.GroupID;
            entity.ContactID = user.ContactID;
            entity.UserName = user.UserName;
            entity.Password = user.Password;
            entity.IsActive = user.IsActive;
            entity.AddressID = null;
            _Context.SaveChanges();
            return entity.ID;
        }
		
		#region Helper Methods
        //public ActionResult List()
        //{
        //    var GenderList = new SelectList(new[]
        //                                  {
        //                                      new {ID="1",Name="name1"},
        //                                      new{ID="2",Name="name2"},
        //                                      new{ID="3",Name="name3"},
        //                                  },
        //                    "ID", "Name", 1);
        //    ViewData["GenderList"] = GenderList;
        //    return View();

        //}

        public ActionResult Gender()
        {
            

            return Gender();
        }
        #endregion			
    }
}
